#include "Mutex.hpp"

using namespace MutexModlue;

int ticket = 1000;

class ThreadData
{
public:
    ThreadData(const std::string& n, Mutex& mutex):name(n), lockp(&mutex)
    {}
    ~ThreadData()
    {}
    std::string name;
    Mutex* lockp;
};

void* route(void* args)
{
    ThreadData* td = static_cast<ThreadData*>(args);
    while(1)
    {
        LockGuard guard(*td->lockp);
        if(ticket > 0)
        {
            usleep(1000);
            printf("%s sells ticket, left: %d\n", td->name.c_str(), ticket);
            ticket--;
        }
        else
            break;
        
        usleep(123);
    }

    return nullptr;
}



int main()
{
    Mutex lock;
    pthread_t t1, t2, t3, t4;
    
    ThreadData* td1 = new ThreadData("thread-1", lock);
    pthread_create(&t1, nullptr, route, td1);
    ThreadData* td2 = new ThreadData("thread-2", lock);
    pthread_create(&t2, nullptr, route, td2);
    ThreadData* td3 = new ThreadData("thread-3", lock);
    pthread_create(&t3, nullptr, route, td3);
    ThreadData* td4 = new ThreadData("thread-4", lock);
    pthread_create(&t4, nullptr, route, td4);

    pthread_join(t1, nullptr);
    pthread_join(t2, nullptr);
    pthread_join(t3, nullptr);
    pthread_join(t4, nullptr);

    return 0;
}